package com.lottery.material.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * Description：自定义全局异常处理器
 * Created by 朱正磊 on 2019-04-13 16:32
 */
@Slf4j
public class MyExceptionResolver implements HandlerExceptionResolver {

    /**
     * description：自定义异常处理
     * user 朱正磊
     * time 2019-04-13 16:41
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器
     * @param e 异常对象
     * @return 返回ModelAndView
     */
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
        if (e instanceof CustomException) {
            CustomException customException = (CustomException) e;
            ModelAndView mv = new ModelAndView();
            FastJsonJsonView view = new FastJsonJsonView();
            Map<String, Object> attributes = new HashMap<>();
            attributes.put("code", customException.getCode());
            attributes.put("msg", customException.getMessage());
            view.setAttributesMap(attributes);
            mv.setView(view);
            return mv;
        } else {
            log.info("==============【异常开始】=============");
            e.printStackTrace();
            log.info("===============【异常结束】==============");
            ModelAndView mv = new ModelAndView("error");
            mv.addObject("exception", e.toString().replaceAll("\n", "<br/>"));
            return mv;
        }
    }

}
